<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编号" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单类型" prop="workType">
        <el-select v-model="queryParams.workType" placeholder="请选择工单类型" clearable>
          <el-option v-for="dict in dict.type.order_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option v-for="dict in dict.type.order_priority" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户号" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['service:newWorkOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['service:newWorkOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['service:newWorkOrder:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['service:newWorkOrder:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newWorkOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="工单编号" align="center" prop="orderId" />
      <!-- <el-table-column label="工单状态" align="center" prop="statue">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_statue" :value="scope.row.statue"/>
        </template>
      </el-table-column> -->
      <el-table-column label="工单类型" align="center" prop="workType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_type" :value="scope.row.workType" />
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_priority" :value="scope.row.priority" />
        </template>
      </el-table-column>
      <el-table-column label="用户号" align="center" prop="userId" />
      <!-- <el-table-column label="用户名" align="center" prop="userName" /> -->
      <!-- <el-table-column label="发起部门id" align="center" prop="startDeptId" /> -->
      <el-table-column label="发起部门" align="center" prop="startDept" />
      <!-- <el-table-column label="发起人id" align="center" prop="startUserId" /> -->
      <el-table-column label="发起人" align="center" prop="startUser" />
      <!-- <el-table-column label="承办部门di" align="center" prop="endDeptId" /> -->
      <el-table-column label="承办部门" align="center" prop="endDept">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.end_dept" :value="scope.row.endDept" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="承办人id" align="center" prop="endUserId" />
      <el-table-column label="承办人" align="center" prop="endUser" /> -->
      <el-table-column label="工单标题" align="center" prop="title" />
      <el-table-column label="联系事项" align="center" prop="matter" width="150" />
      <el-table-column label="内容摘要" align="center" prop="content" width="400" />
      <!-- <el-table-column label="附件" align="center" prop="attachment" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <!-- <el-table-column label="提交内容" align="center" prop="commitContent" /> -->
      <!-- <el-table-column label="提交图片" align="center" prop="commitPic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.commitPic" :width="50" :height="50"/>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['service:newWorkOrder:edit']">附件查看</el-button><br>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="getOrderRecordList(scope.row)"
            v-hasPermi="['service:newWorkOrder:edit']">全部意见</el-button><br>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="editOrderRecordList(scope.row)"
            v-hasPermi="['service:newWorkOrder:edit']">输入意见</el-button><br>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateResult(scope.row)"
            v-hasPermi="['service:newWorkOrder:edit']">处理结果</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['service:newWorkOrder:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工作工单对话框 -->
    <el-dialog :title="title" :visible.sync="openResult" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="处理内容" prop="commitContent">
          <el-input v-model="form.commitContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="处理图片" prop="commitPic">
          <image-upload v-model="form.commitPic" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">处 理</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="附件" prop="attachment">
          <file-upload v-model="form.attachment" />
        </el-form-item>
        <div style="color: #f56c6c; font-size: 15px; margin-top: 4px;">
          <i class="el-icon-warning-outline"></i> 若有提交附件点击可进行查看
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>


    <!-- 添加意见信息 -->
    <el-dialog :title="title" :visible.sync="erpWorkOpenAdd" width="500px" append-to-body>
      <el-form ref="erpWorkForm" :model="erpWorkForm" :rules="rules" label-width="80px">
        <el-form-item label="意见内容" prop="recordContent">
          <el-input v-model="erpWorkForm.recordContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormRecord">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 查看意见信息 -->
    <el-dialog :title="title" :visible.sync="erpWorkOpen" width="800px" append-to-body>
      <el-table v-loading="loading" :data="workRecordList" @selection-change="handleSelectionChange">
        <el-table-column label="意见内容" align="center" prop="recordContent" width="300" />
        <el-table-column label="意见部门" align="center" prop="recordDeptName" />
        <el-table-column label="意见人员" align="center" prop="recordUserName" />
        <el-table-column label="意见时间" align="center" prop="createTime" />
        <el-table-column label="提交状态" align="center" prop="recordStatue">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.record_statue" :value="scope.row.recordStatue" />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>



  </div>
</template>

<script>
  import { listNewWorkOrder, getNewWorkOrder, delNewWorkOrder, addNewWorkOrder, updateNewWorkOrder } from "@/api/service/newWorkOrder";
  import { listOrderRecord, updateOrderRecord, addOrderRecord } from "@/api/service/orderRecord";
  import { getUserProfile } from "@/api/system/user";

  export default {
    name: "NewWorkOrder",
    dicts: ['order_statue', 'order_priority', 'end_dept', 'order_type', 'record_statue'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 工作工单表格数据
        newWorkOrderList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openResult: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderId: null,
          statue: 5,
          workType: null,
          priority: null,
          userId: null,
          userName: null,
          startDeptId: null,
          startDept: null,
          startUserId: null,
          startUser: null,
          endDeptId: null,
          endDept: null,
          endUserId: null,
          endUser: null,
          matter: null,
          title: null,
          content: null,
          attachment: null,
          commitContent: null,
          commitPic: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        },
        tempOrderId: null,
        tempDept: null,
        erpWorkForm: {},
        erpWorkOpenAdd: false,
        erpWorkOpen: false,
        // 工单意见查询参数
        queryParamserpWork: {
          pageNum: 1,
          pageSize: 20,
          orderId: null
        },
        // 工单意见表格数据
        workRecordList: [],
      };
    },
    created() {
      // this.getUserInfo();
      this.getList();
    },
    methods: {
      /** 查询工作工单列表 */
       async getList() {
        this.loading = true;
        // 先确保获取用户信息
        await this.getUserInfo();
        listNewWorkOrder(this.queryParams).then(response => {
          this.newWorkOrderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      async getUserInfo() {
        try {
          const response = await getUserProfile();
          this.queryParams.endUserId = response.data.userId;
          return Promise.resolve();
        } catch (error) {
          console.error('获取用户信息失败:', error);
          return Promise.reject(error);
        }
      },
      // getUserInfo() {
      //   getUserProfile().then(response => {
      //     this.queryParams.endUserId = response.data.userId;
      //     this.getList();
      //   });
      // },
      // 取消按钮
      cancel() {
        this.open = false;
        this.openResult = false;
        this.erpWorkOpenAdd = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.tempOrderId = null;
        this.tempDept = null;
        this.form = {
          id: null,
          orderId: null,
          startDeptId: null,
          startDept: null,
          startUserId: null,
          startUser: null,
          endDeptId: null,
          endDept: null,
          endUserId: null,
          endUser: null,
          matter: null,
          content: null,
          remark: null,
          statue: null,
          attachment: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
        this.erpWorkForm = {
          id: null,
          orderId: null,
          recordDeptId: null,
          recordDeptName: null,
          recordUserId: null,
          recordUserName: null,
          recordContent: null,
          recordTime: null,
          recordStatue: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("erpWorkForm");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加工作工单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getNewWorkOrder(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "查看附件";
        });
      },

      handleUpdateResult(row) {
        this.reset();
        const id = row.id || this.ids
        getNewWorkOrder(id).then(response => {
          this.form = response.data;
          this.openResult = true;
          this.title = "处理结果";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              this.form.statue = 6;
              updateNewWorkOrder(this.form).then(response => {
                this.$modal.msgSuccess("提交成功");
                this.open = false;
                this.openResult = false;
                this.getList();
              });
            } else {
              addNewWorkOrder(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.openResult = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除工作工单编号为"' + ids + '"的数据项？').then(function () {
          return delNewWorkOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('service/newWorkOrder/export', {
          ...this.queryParams
        }, `newWorkOrder_${new Date().getTime()}.xlsx`)
      },
      /** 添加工单意见 */
      editOrderRecordList(row) {
        this.reset();
        this.tempOrderId = row.id;
        this.tempDept = row.endDept;
        this.erpWorkForm.orderId = row.orderId;
        this.erpWorkForm.recordStatue = 2;
        this.erpWorkOpenAdd = true;
        this.title = "添加意见"
      },
      /** 意见提交按钮 */
      submitFormRecord() {
        this.$refs["erpWorkForm"].validate(valid => {
          if (valid) {
            this.erpWorkForm.recordStatue = 2;
            this.erpWorkForm.recordDeptName = this.tempDept;
            addOrderRecord(this.erpWorkForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.erpWorkOpenAdd = false;
              this.updateParams.id = this.tempOrderId;
              this.updateParams.statue = 5;
              updateNewWorkOrder(this.updateParams).then(response => {
                this.getList();
              });
              // this.getList();
            });
          }
        });
      },
      /** 查询工单意见列表 */
      getOrderRecordList(row) {
        this.loading = true;
        this.queryParamserpWork.orderId = row.orderId;
        listOrderRecord(this.queryParamserpWork).then(response => {
          this.workRecordList = response.rows;
          this.erpWorkOpen = true;
          this.loading = false;
        });
      },
    }
  };
</script>